import { Injectable } from '@angular/core';
import 'rxjs/add/operator/toPromise';
import {Http, Headers, Response, RequestOptions} from '@angular/http'
import {Router} from "@angular/router";
import {FrontUser} from "../entity/User";
import {CommonIp} from "../entity/Ip";
@Injectable()
export class LoginService extends CommonIp{
  public verificationCode=this.userIp+"/servlet/validateCodeServlet";
  public resetPasURL=this.userIp+"/p/User/updatecode";
  public registerUser=this.userIp+"/p/User/UserReg";
  constructor(public http:Http,public router:Router){
    super();
  }
  public RegisterUser(user:FrontUser):Promise<void>{
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers:headers});
    return this.http.post(this.registerUser,JSON.stringify(user),options)
      .toPromise()
      .then(res => {
        if(res.status<200||res.status>=300){
          throw  new Error('Bad response status:'+res.status);
        }

        if(res.json().code == 1011){
          $.jBox.tip("验证码错误，可以点击刷新验证码，重新输入。");
        }
        if(res.json().code==200){
          this.router.navigate(['/isLogin']);
          $.jBox.tip("请登陆您的邮箱并激活发送的链接，然后登陆");
        }else if(res.json().code==1012){
          $.jBox.tip("邮箱已经被注册");
        }
        else if(res.json().code==1111){
          $.jBox.tip("请输入完整内容");
        }
        else  if (res.json().code==1005){
          $.jBox.tip("注册失败请重新注册");
        }else if(res.json().code==1004){
          $.jBox.tip("抱歉邮箱发送失败,请重新注册");
        }
      })

      .catch(this.handleError)
  }
  public ResetPas(user:FrontUser):Promise<void>{
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers:headers});
    return this.http.post(this.resetPasURL,JSON.stringify(user),options)
      .toPromise()
      .then(res => {
        if(res.status<200||res.status>=300){
          throw  new Error('Bad response status:'+res.status);
        }
        if(res.json().code==200){
          this.router.navigate(['/isLogin']);
        }else {
          $.jBox.tip("重置密码失败");
        }
      })

      .catch(this.handleError)

  }
  public VerificationCode(code:string,random:string){
    return this.http.get(this.verificationCode+"?validateCode="+code+"&random="+random)
      .toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }
  public extractData(res: Response):Promise<boolean>{
    if(res.status<200||res.status>=300){
      throw new Error('Bad response status:'+res.status);
    }

    let body  = res.json();

    return body||{};
  }
  public SendEmailCode(email:string):Promise<string>{
    return this.http.get(this.userIp+"/p/User/"+email+"/forget")
      .toPromise()
      .then(res=>{
        if(res.status<200||res.status>=300){
          throw  new Error('Bad response status:'+res.status);
        }
        if(res.json().code==200){

          return "邮件发送成功";
        }else {

          return "邮件发送失败";

        }
      })
  }
  public VarificationEmailCode(code:string,email:string):Promise<void>{
    return this.http.get(this.userIp+"/p/User/"+code+"/"+email+"/testcode")
      .toPromise()
      .then(res=>{
        if(res.status<200||res.status>=300){
          throw  new Error('Bad response status:'+res.status);
        }
        if(res.json().code==200){
          sessionStorage.removeItem("forgetEmail");
          this.router.navigate(['/reset']);
        }else{
          $.jBox.tip("验证码错误");
        }
      })
      .catch(this.handleError);
  }
  private  extreinforEntity(res:Response){
    if(res.status<200||res.status>=300){
      throw  new Error('Bad response status:'+res.status);
    }
    let body=res.json();

    return body;
  }
  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }

}
